<!-- 登录组件 -->
<template>
    <div class="login_container">
        <!--title 对话框左上角标题，v-modol控制对话框显示与隐藏     想用第一种清空表单的方法加上close事件就好 @close="close"-->
        <el-dialog v-model="userStore.visiable" title="用户登录">
            <el-row>
                <!--左侧结构：收集号码登录、微信扫一扫登录-->
                <el-col :span="12">
                    <div class="login">
                        <div v-show="scene == 0">
                            <el-form ref="formRef" :model="loginParam" :rules="rules">
                                <el-form-item prop="phone">
                                    <el-input placeholder="请输入手机号码" :prefix-icon="User"
                                        v-model="loginParam.phone"></el-input>
                                </el-form-item>
                                <el-form-item prop="code">
                                    <el-input placeholder="请输入验证码" :prefix-icon="Lock" v-model="loginParam.code"></el-input>
                                </el-form-item>
                                <el-form-item>
                                    <el-button :disabled="!isPhone || flag ? true : false">
                                        <CountDown v-if="flag" :flag="flag" @getFlag="getFlag" />
                                        <span v-else @click="getCode">获取验证码</span>
                                    </el-button>
                                </el-form-item>
                            </el-form>
                            <el-button style="width: 100%;" type="primary" size="default"
                                :disabled="!isPhone || loginParam.code.length !== 6" @click="login">用户登录</el-button>
                            <div class="bottom">
                                <p>微信扫码登录</p>
                                <svg @click="changeScene" t="1697422620157" class="icon" style="cursor: pointer;"
                                    viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="4007"
                                    width="32" height="32">
                                    <path
                                        d="M347.729118 353.0242c-16.487119 0-29.776737 13.389539-29.776737 29.776737S331.241998 412.677596 347.729118 412.677596s29.776737-13.389539 29.776737-29.776737-13.289617-29.876659-29.776737-29.876659zM577.749415 511.800156c-13.689305 0-24.880562 11.091335-24.880563 24.880562 0 13.689305 11.091335 24.880562 24.880563 24.880562 13.689305 0 24.880562-11.191257 24.880562-24.880562s-11.191257-24.880562-24.880562-24.880562zM500.909446 412.677596c16.487119 0 29.776737-13.389539 29.776737-29.776737s-13.389539-29.776737-29.776737-29.776737c-16.487119 0-29.776737 13.389539-29.776737 29.776737s13.289617 29.776737 29.776737 29.776737zM698.455113 511.600312c-13.689305 0-24.880562 11.091335-24.880562 24.880562 0 13.689305 11.091335 24.880562 24.880562 24.880562 13.689305 0 24.880562-11.091335 24.880562-24.880562-0.099922-13.689305-11.191257-24.880562-24.880562-24.880562z"
                                        fill="#00C800" p-id="4008"></path>
                                    <path
                                        d="M511.601093 0.799375C229.12178 0.799375 0.000781 229.820453 0.000781 512.399688s229.021077 511.600312 511.600312 511.600312 511.600312-229.021077 511.600312-511.600312S794.180328 0.799375 511.601093 0.799375z m-90.229508 634.504294c-27.37861 0-49.361436-5.595628-76.839969-10.991413l-76.640125 38.469945 21.882904-65.948477c-54.957065-38.370023-87.73146-87.831382-87.73146-148.084309 0-104.318501 98.722873-186.554254 219.32865-186.554255 107.815769 0 202.34192 65.648712 221.327088 153.979703-6.994536-0.799375-13.989071-1.298985-21.083529-1.298985-104.118657 0-186.454333 77.739266-186.454332 173.564403 0 15.98751 2.498048 31.275566 6.794692 45.964091-6.794692 0.599532-13.689305 0.899297-20.583919 0.899297z m323.547228 76.839969l16.48712 54.757221-60.153006-32.874317c-21.882904 5.495706-43.965652 10.991413-65.848555 10.991413-104.318501 0-186.554254-71.344262-186.554255-159.175644 0-87.631538 82.135831-159.175644 186.554255-159.175644 98.523029 0 186.254489 71.444184 186.254488 159.175644 0.099922 49.461358-32.774395 93.227166-76.740047 126.301327z"
                                        fill="#00C800" p-id="4009"></path>
                                </svg>
                            </div>
                        </div>
                        <div class="webchat" v-show="scene == 1">
                            <div id="login_container"></div>
                            <div class="phone">
                                <p>手机短信验证码登录</p>
                                <svg @click="handler" style="cursor: pointer;" t="1697423067758" class="icon"
                                    viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="6120"
                                    width="32" height="32">
                                    <path
                                        d="M820.409449 797.228346q0 25.19685-10.07874 46.866142t-27.716535 38.299213-41.322835 26.204724-50.897638 9.574803l-357.795276 0q-27.212598 0-50.897638-9.574803t-41.322835-26.204724-27.716535-38.299213-10.07874-46.866142l0-675.275591q0-25.19685 10.07874-47.370079t27.716535-38.80315 41.322835-26.204724 50.897638-9.574803l357.795276 0q27.212598 0 50.897638 9.574803t41.322835 26.204724 27.716535 38.80315 10.07874 47.370079l0 675.275591zM738.771654 170.330709l-455.559055 0 0 577.511811 455.559055 0 0-577.511811zM510.992126 776.062992q-21.165354 0-36.787402 15.11811t-15.622047 37.291339q0 21.165354 15.622047 36.787402t36.787402 15.622047q22.173228 0 37.291339-15.622047t15.11811-36.787402q0-22.173228-15.11811-37.291339t-37.291339-15.11811zM591.622047 84.661417q0-8.062992-5.03937-12.598425t-11.086614-4.535433l-128 0q-5.03937 0-10.582677 4.535433t-5.543307 12.598425 5.03937 12.598425 11.086614 4.535433l128 0q6.047244 0 11.086614-4.535433t5.03937-12.598425z"
                                        p-id="6121" fill="#f4ea2a"></path>
                                </svg>
                            </div>
                        </div>
                    </div>
                </el-col>
                <el-col :span="12">
                    <div class="leftContent">
                        <div class="top">
                            <div class="item">
                                <img src="../../assets/images/code_app.png" alt="" srcset="">
                                <svg t="1697422620157" class="icon" viewBox="0 0 1024 1024" version="1.1"
                                    xmlns="http://www.w3.org/2000/svg" p-id="4007" width="16" height="16">
                                    <path
                                        d="M347.729118 353.0242c-16.487119 0-29.776737 13.389539-29.776737 29.776737S331.241998 412.677596 347.729118 412.677596s29.776737-13.389539 29.776737-29.776737-13.289617-29.876659-29.776737-29.876659zM577.749415 511.800156c-13.689305 0-24.880562 11.091335-24.880563 24.880562 0 13.689305 11.091335 24.880562 24.880563 24.880562 13.689305 0 24.880562-11.191257 24.880562-24.880562s-11.191257-24.880562-24.880562-24.880562zM500.909446 412.677596c16.487119 0 29.776737-13.389539 29.776737-29.776737s-13.389539-29.776737-29.776737-29.776737c-16.487119 0-29.776737 13.389539-29.776737 29.776737s13.289617 29.776737 29.776737 29.776737zM698.455113 511.600312c-13.689305 0-24.880562 11.091335-24.880562 24.880562 0 13.689305 11.091335 24.880562 24.880562 24.880562 13.689305 0 24.880562-11.091335 24.880562-24.880562-0.099922-13.689305-11.191257-24.880562-24.880562-24.880562z"
                                        fill="#bfbfbf" p-id="4008"></path>
                                    <path
                                        d="M511.601093 0.799375C229.12178 0.799375 0.000781 229.820453 0.000781 512.399688s229.021077 511.600312 511.600312 511.600312 511.600312-229.021077 511.600312-511.600312S794.180328 0.799375 511.601093 0.799375z m-90.229508 634.504294c-27.37861 0-49.361436-5.595628-76.839969-10.991413l-76.640125 38.469945 21.882904-65.948477c-54.957065-38.370023-87.73146-87.831382-87.73146-148.084309 0-104.318501 98.722873-186.554254 219.32865-186.554255 107.815769 0 202.34192 65.648712 221.327088 153.979703-6.994536-0.799375-13.989071-1.298985-21.083529-1.298985-104.118657 0-186.454333 77.739266-186.454332 173.564403 0 15.98751 2.498048 31.275566 6.794692 45.964091-6.794692 0.599532-13.689305 0.899297-20.583919 0.899297z m323.547228 76.839969l16.48712 54.757221-60.153006-32.874317c-21.882904 5.495706-43.965652 10.991413-65.848555 10.991413-104.318501 0-186.554254-71.344262-186.554255-159.175644 0-87.631538 82.135831-159.175644 186.554255-159.175644 98.523029 0 186.254489 71.444184 186.254488 159.175644 0.099922 49.461358-32.774395 93.227166-76.740047 126.301327z"
                                        fill="#bfbfbf" p-id="4009"></path>
                                </svg>
                                <p>微信扫一扫关注</p>
                                <p>快速预约挂号</p>
                            </div>
                            <div class="item">
                                <img src="../../assets/images/code_login_wechat.png" alt="" srcset="">
                                <svg t="1697423067758" class="icon" viewBox="0 0 1024 1024" version="1.1"
                                    xmlns="http://www.w3.org/2000/svg" p-id="6120" width="16" height="16">
                                    <path
                                        d="M820.409449 797.228346q0 25.19685-10.07874 46.866142t-27.716535 38.299213-41.322835 26.204724-50.897638 9.574803l-357.795276 0q-27.212598 0-50.897638-9.574803t-41.322835-26.204724-27.716535-38.299213-10.07874-46.866142l0-675.275591q0-25.19685 10.07874-47.370079t27.716535-38.80315 41.322835-26.204724 50.897638-9.574803l357.795276 0q27.212598 0 50.897638 9.574803t41.322835 26.204724 27.716535 38.80315 10.07874 47.370079l0 675.275591zM738.771654 170.330709l-455.559055 0 0 577.511811 455.559055 0 0-577.511811zM510.992126 776.062992q-21.165354 0-36.787402 15.11811t-15.622047 37.291339q0 21.165354 15.622047 36.787402t36.787402 15.622047q22.173228 0 37.291339-15.622047t15.11811-36.787402q0-22.173228-15.11811-37.291339t-37.291339-15.11811zM591.622047 84.661417q0-8.062992-5.03937-12.598425t-11.086614-4.535433l-128 0q-5.03937 0-10.582677 4.535433t-5.543307 12.598425 5.03937 12.598425 11.086614 4.535433l128 0q6.047244 0 11.086614-4.535433t5.03937-12.598425z"
                                        p-id="6121" fill="#bfbfbf"></path>
                                </svg>
                                <p>扫一扫下载</p>
                                <p>“预约挂号”APP</p>
                            </div>
                        </div>
                        <p class="tip">尚医通官方指定平台</p>
                        <p class="tip">快速挂号 安全放心</p>
                    </div>
                </el-col>
            </el-row>
            <template #footer>
                <span class="dialog-footer">
                    <el-button type="primary" size="default" @click="closeDialog">
                        关闭窗口
                    </el-button>
                </span>
            </template>
        </el-dialog>
    </div>
</template>

<script setup lang="ts">
//引入微信扫码登录参数请求
import { reqWxLogin } from '@/api/hospital/index'
import type { WXLoginResponseData } from '@/api/hospital/type'
import { ref, reactive, computed, watch } from 'vue'
//引入图标库
import { User, Lock } from '@element-plus/icons-vue'
//引入倒计时组件
import CountDown from '@/components/countdown/index.vue'

//获取user仓库的数据（visiable）可以控制login组件的对话框显示与隐藏
import useUserStore from '@/store/modules/user';
import { ElMessage, FormRules } from 'element-plus';
import { useRoute, useRouter } from 'vue-router'
//获取路由器对象
let $router = useRouter();
let $route = useRoute();


let userStore = useUserStore();

//定义一个响应式数据控制倒计时组件显示与隐藏
let flag = ref<boolean>(false);     //如果flag为真，开启倒计时，flag为假并非倒计时


let scene = ref<number>(0)  //0代表收集号码登录， 如果是1 微信扫码登录

//获取form组件实例
let formRef = ref<any>()

//收集表单数据----手机号码
let loginParam = reactive({
    phone: '',//收集手机号码
    code: '',//收集手机验证码
})

//计算出当前表单元素收集的内容是否手机号码格式
let isPhone = computed(() => {
    //手机号码正则表达式
    const reg = /^1((34[0-8])|(8\d{2})|(([35][0-35-9]|4[579]|66|7[35678]|9[1389])\d{1}))\d{7}$/;
    //返回布尔值：真代表手机号码，假即为不是手机号码
    return reg.test(loginParam.phone);
})

//点击微信扫码登录|微信小图标切换为微信扫码登录
const changeScene = async () => {
    //切换场景为1
    scene.value = 1;
    //发请求获取微信扫码二维码需要参数
    //咱们在想硅谷学校的服务器发请求,获取微信扫码登录页面参数
    //还需要携带一个参数:告诉学校服务器用户授权成功以后重定向项目某一个页面 进行编码，后台需要的是编码后的路由
    let redirect_URL = encodeURIComponent(window.location.origin + "/wxlogin");
    let result: WXLoginResponseData = await reqWxLogin(redirect_URL);
    //生成微信扫码登录二维码页面
    //忽略ts检测
    //@ts-ignore
    new WxLogin({
        self_redirect: true, //true:手机点击确认登录后可以在 iframe 内跳转到 redirect_uri
        id: "login_container", //显示二维码容器设置
        appid: result.data.appid, //应用位置标识appid
        scope: "snsapi_login", //当前微信扫码登录页面已经授权了
        redirect_uri: result.data.redirectUri, //填写授权回调域路径,就是用户授权成功以后，微信服务器向公司后台推送code地址
        state: result.data.state, //state就是学校服务器重定向的地址携带用户信息
        style: "black",
        href: "",
    });
}

//获取验证码按钮的回调
const getCode = async () => {

    // console.log(isPhone.value)
    // console.log(flag.value)

    //解决element-plus按钮禁用还能点击的问题
    if (!isPhone.value || flag.value) {
        return
    }

    //开启倒计时模式    倒计时组件显示出来
    flag.value = true;
    //通知pinia仓库存储验证码

    try {
        //获取验证码成功.
        await userStore.getCode(loginParam.phone);
        loginParam.code = userStore.code;

    } catch (error) {
        // 获取验证码失败 
        ElMessage({
            type: "error",
            message: (error as Error).message
        })
    }

}

//计数器子组件绑定的自定义事件
//当倒计时为零的时候，通知父组件倒计时组件隐藏
const getFlag = (val: boolean) => {
    //倒计时模式结束
    flag.value = val
}

//点击用户登录按钮的回调
const login = async () => {
    //点击登录，校验表单规则 保证表单校验两项都符合条件
    await formRef.value.validate();

    //发起登录请求
    //登录请求成功：顶部组件需要展示用户名字、对话框关闭
    //登录请求失败：弹出对应登录失败的错误信息
    try {
        //用户登录成功
        await userStore.userLogin(loginParam);
        //关闭对话框
        userStore.visiable = false;
        //获取url的query的参数
        let redirect = $route.query.redirect;
        if (redirect) {
            $router.push(redirect as string);
        } else {
            $router.push('/home')
        }
    } catch (error) {
        ElMessage({
            type: 'error',
            message: (error as Error).message
        })
    }
}

//自定义校验规则：手机号码自定义校验规则
const validatorPhone = (rule: any, value: any, callback: any) => {
    //rule：表单校验规则对象
    //value：当前文本的内容
    //callback：回调函数
    //手机号码正则表达式
    const reg = /^1((34[0-8])|(8\d{2})|(([35][0-35-9]|4[579]|66|7[35678]|9[1389])\d{1}))\d{7}$/;
    if (reg.test(value)) {
        callback();
    } else {
        callback(new Error('请输入正确的手机号码'))
    }

}

//自定义校验规则：验证码自定义校验规则
const validatorCode = (rule: any, value: any, callback: any) => {
    //rule：表单校验规则对象
    //value：当前文本的内容
    //callback：回调函数
    //手机号码正则表达式
    if (/^\d{6}$/.test(value)) {
        callback();
    } else {
        callback(new Error('请输入正确的验证码格式'))
    }

}


//表单校验的规则对象
const rules = reactive<FormRules<typeof loginParam>>({
    //手机号码验证
    //required  代表当前字段务必进行校验
    //message   代表校验错误的提示信息
    //trigger   代表表单校验的时机  change：文本发生变化时触发  blur：失去焦点的时候触发
    //min：代表是最小位数    max：代表是最大的位数
    // phone: [
    //     { required: true, message: '请输入正确手机号', trigger: 'change', min: 11 },
    // ],
    // code: [
    //     { required: true, message: '验证码务必6位', trigger: 'blur', min: 6 },
    // ]

    phone: [{ trigger: 'change', validator: validatorPhone }],
    code: [{ trigger: 'blur', validator: validatorCode }]
})

/*第一种方法，利用dialog关闭触发的事件，手动清空表单*/
/*第二种方法，利用v-if创建dialog，，自动清空表单*/

//对话框关闭事件的回调 （第一种方法需要）
// const close = () => {
//     //清空收集的数组
//     Object.assign(loginParam, { phone: '', code: '' });
//     //清除上一次校验的结果
//     formRef.value.resetFields()
// }

const closeDialog = () => {
    //第一种方法需要
    // //清空收集的数组
    // Object.assign(loginParam, { phone: '', code: '' });
    // //清除上一次校验的结果
    // formRef.value.resetFields()
    //关闭对话框
    userStore.visiable = false
}

//点击手机短信验证码登录
const handler = () => {
    scene.value = 0
}

//监听场景的数据
watch(() => scene.value, (val: number) => {
    if (val === 1) {
        userStore.queryState();
    }
})

</script>

<style lang="scss" scoped>
.login_container {
    ::v-deep(.el-dialog__body) {
        border-top: 1px solid #ccc;
        border-bottom: 1px solid #ccc;
    }

    .login {
        padding: 20px;
        border: 1px solid #ccc;

        .webchat {
            display: flex;
            justify-content: center;
            align-items: center;
            flex-direction: column;
            text-align: center;

            .phone {

                p {
                    margin: 10px 0px;
                }
            }
        }


        .bottom {
            display: flex;
            flex-direction: column;
            align-items: center;

            p {
                margin: 10px 0px;
            }
        }
    }

    .leftContent {
        .top {
            display: flex;
            justify-content: space-around;

            .item {
                display: flex;
                flex-direction: column;
                align-items: center;

                img {
                    width: 130px;
                    height: 130px;
                    margin-bottom: 10px;
                }

                p {
                    margin: 5px 0px;
                }
            }
        }
    }

    .tip {
        font-size: 20px;
        font-weight: 900;
        text-align: center;
        margin: 20px 0px;
    }
}
</style>